package com.niiwoo.civet.user.service.local.myCustomer;

import com.niiwoo.civet.user.constants.UserRedisKey;
import com.niiwoo.civet.user.dao.entity.*;
import com.niiwoo.civet.user.dao.mapper.*;
import com.niiwoo.civet.user.dto.request.NiiwooScorePageRequestDTO;
import com.niiwoo.civet.user.dto.request.myCustomer.*;
import com.niiwoo.civet.user.dto.response.myCustomer.*;
import com.niiwoo.civet.user.enums.*;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by laichunjing on 2018/4/30
 */
@Service
@Slf4j
public class MyCustomerInfoService {

    //日期格式化
    private FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd");

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    UserQuestionIdentityMapperExt userQuestionIdentityMapperExt;
    @Autowired
    UserQuestionFeedBackMapper userQuestionFeedBackMapper;
    @Autowired
    UserQuestionMapper userQuestionMapper;
    @Autowired
    UserBasicInfoMapperExt userBasicInfoMapperExt;
    @Autowired
    UserQuestionKeyIdentityMapperExt userQuestionKeyIdentityMapperExt;
    @Autowired
    UserQuestionKeyMapper userQuestionKeyMapper;
    @Autowired
    UserQuestionMapperExt userQuestionMapperExt;
    @Autowired
    UserQuestionKeyRelationMapperExt userQuestionKeyRelationMapperExt;
    @Autowired
    UserQuestionFeedBackMapperExt userQuestionFeedBackMapperExt;
    @Autowired
    UserNewFeedBackMapperExt userNewFeedBackMapperExt;
    @Autowired
    UserFeedBackImageMapper userFeedBackImageMapper;
    @Autowired
    UserFeedBackAppendMapperExt userFeedBackAppendMapperExt;
    @Autowired
    UserFeedBackImageMapperExt userFeedBackImageMapperExt;
    @Autowired
    RedisTemplate<String, String > redisTemplate;

    /**
     * 客服首页信息
     * @param userId
     * @return
     */
    public MyCustomerHomePageResponseDTO myCustomerHomePageList(String userId) {
        MyCustomerHomePageResponseDTO myCustomerHomePageResponseDTO = new MyCustomerHomePageResponseDTO();
        List<ProblemResponseDTO> investHotProblemsList=new ArrayList<>();
        List<ProblemResponseDTO> borrowHotProblemsList=new ArrayList<>();
        List<KeyWordResponseDTO> KeywordList = new ArrayList<>();

        UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);
        UserNewFeedBack userNewFeedBack=userNewFeedBackMapperExt.selectFeedBackIsNewStatus(userId);
        if(userNewFeedBack==null||StringUtils.isEmpty(userId)){
            myCustomerHomePageResponseDTO.setIsNewReceive((byte)0);
        }else{
            myCustomerHomePageResponseDTO.setIsNewReceive((byte)1);
        }

        QuestionIdentityTagEnum questionIdentityTagEnum = queryUserIdentity(userBasicInfo);
        //身份状态
        myCustomerHomePageResponseDTO.setIdentityStatus(questionIdentityTagEnum.getValue());
        if(userBasicInfo!=null){
            myCustomerHomePageResponseDTO.setUserName(userBasicInfo.getNickName());
        }else{
            myCustomerHomePageResponseDTO.setUserName(null);
        }
        //按更新时间排序前五
        List<UserQuestion>  userQuestionOrder=userQuestionMapperExt.selectByPrimaryKeyOrder();
        log.info("userQuestionOrder info {}"+userQuestionOrder.toArray());
        //投资相关
        List<UserQuestionIdentity> UserQuestionInvestIdentityList=userQuestionIdentityMapperExt.selectHotProblemByUserTag(questionIdentityTagEnum.getValue()
                ,QuestionRelevantEnum.INVESTOR.getValue());
        log.info("投资相关 UserQuestionInvestIdentityList info {}"+UserQuestionInvestIdentityList.toArray());
        for(UserQuestionIdentity userQuestionIdentity:UserQuestionInvestIdentityList){
            ProblemResponseDTO problemResponseDTO=new ProblemResponseDTO();
            problemResponseDTO.setRelationType(userQuestionIdentity.getRelevant());
            UserQuestion userQuestion=userQuestionMapper.selectByPrimaryKey(userQuestionIdentity.getQuestionId());
            if(userQuestion!=null){
                problemResponseDTO.setId(userQuestion.getId());
                problemResponseDTO.setProblemName(userQuestion.getTitle());
            }
            for(UserQuestion res:userQuestionOrder){
                if(userQuestionIdentity.getQuestionId().equals(res.getId())){
                    problemResponseDTO.setIsNew((byte)1);
                    break;
                }else{
                    problemResponseDTO.setIsNew((byte)0);
                }
            }

            investHotProblemsList.add(problemResponseDTO);
        }
        myCustomerHomePageResponseDTO.setInvestHotProblemsList(investHotProblemsList);

        //借款相关
        List<UserQuestionIdentity> UserQuestionBorrowIdentityList=userQuestionIdentityMapperExt.selectHotProblemByUserTag(questionIdentityTagEnum.getValue()
                ,QuestionRelevantEnum.BORROWER.getValue());
        log.info("借款相关 UserQuestionBorrowIdentityList info {}"+UserQuestionBorrowIdentityList.toArray());
        for(UserQuestionIdentity userQuestionIdentity:UserQuestionBorrowIdentityList){
            ProblemResponseDTO problemResponseDTO=new ProblemResponseDTO();
            problemResponseDTO.setRelationType(userQuestionIdentity.getRelevant());
            UserQuestion userQuestion=userQuestionMapper.selectByPrimaryKey(userQuestionIdentity.getQuestionId());
            if(userQuestion!=null){
                problemResponseDTO.setId(userQuestion.getId());
                problemResponseDTO.setProblemName(userQuestion.getTitle());
            }
            for(UserQuestion res:userQuestionOrder){
                if(userQuestionIdentity.getQuestionId().equals(res.getId())){
                    problemResponseDTO.setIsNew((byte)1);
                    break;
                }else{
                    problemResponseDTO.setIsNew((byte)0);
                }
            }
            borrowHotProblemsList.add(problemResponseDTO);
        }
        myCustomerHomePageResponseDTO.setBorrowHotProblemsList(borrowHotProblemsList);

        // 关键词列表
        List<UserQuestionKeyIdentity> userQuestionKeyIdentityList = userQuestionKeyIdentityMapperExt.selectKeywordByUserTag(questionIdentityTagEnum.getValue());
        log.info("关键词列表 userQuestionKeyIdentityList info {}"+userQuestionKeyIdentityList.toArray());
        for(UserQuestionKeyIdentity userQuestionKeyIdentity:userQuestionKeyIdentityList){
            KeyWordResponseDTO keyWordResponseDTO = new KeyWordResponseDTO();
            UserQuestionKey userQuestionKey = userQuestionKeyMapper.selectByPrimaryKey(userQuestionKeyIdentity.getQuestionKeyId());
            keyWordResponseDTO.setId(userQuestionKey.getId());
            keyWordResponseDTO.setKeyWordName(userQuestionKey.getWord());
            keyWordResponseDTO.setKeyWordImgUrl(userQuestionKey.getImageUrl());
            KeywordList.add(keyWordResponseDTO);
        }
        myCustomerHomePageResponseDTO.setKeywordList(KeywordList);

        return myCustomerHomePageResponseDTO;
    }
    /**
     * 判断用户的身份
     */
    public QuestionIdentityTagEnum  queryUserIdentity(UserBasicInfo userBasicInfo) {

        // 未登录，既是借款人又是投资人返回投资相关(热门问题对应投资人)
        if(userBasicInfo==null){
            return QuestionIdentityTagEnum.INVESTOR;
        }else{
            String identityTagStr = userBasicInfo.getIdentityTag();
            if (UserEnum.IdentityTag.INVEST_BORROWER.getType().equals(identityTagStr)) {
                return QuestionIdentityTagEnum.INVESTOR;
            }else if(UserEnum.IdentityTag.INVESTOR.getType().equals(identityTagStr)){
                return QuestionIdentityTagEnum.INVESTOR;
            }else if(UserEnum.IdentityTag.BORROWER.getType().equals(identityTagStr)){
                return QuestionIdentityTagEnum.BORROWER;
            }else if( UserEnum.IdentityTag.NO_IDENTITY.getType().equals(identityTagStr) ){
                return QuestionIdentityTagEnum.NEW_HAND;
            }
        }
        return null;
    }

    /***
     * 问题搜索
     * @param searchContent
     * @return
     */
    public QueryContentResponseDTO queryProblemsListByContent(String searchContent) {

        List<UserQuestion> userQuestionList = userQuestionMapperExt.selectByContent(searchContent);
        log.info("userQuestionList info{}"+userQuestionList.toArray());
        QueryContentResponseDTO dto = new QueryContentResponseDTO();
        List<ProblemContentResponseDTO> problemList=new ArrayList<>();
        userQuestionList.forEach(res-> {
            ProblemContentResponseDTO problemContentResponseDTO=new ProblemContentResponseDTO();
            problemContentResponseDTO.setId(res.getId());
            problemContentResponseDTO.setProblemTitle(res.getTitle());
            problemList.add(problemContentResponseDTO);
        });
        dto.setProblemList(problemList);
        return dto;
    }

    /**
     * 关键词列表(单独写一个关键词列表接口)
     * @param userId
     * @return
     */
    public KeyWordListResponseDTO queryKeyWordList(String userId) {
        KeyWordListResponseDTO dto = new KeyWordListResponseDTO();
        List<KeyWordResponseDTO> KeywordList = new ArrayList<>();
        UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);

        QuestionIdentityTagEnum questionIdentityTagEnum = queryUserIdentity(userBasicInfo);
        //身份状态
        dto.setIdentityStatus(questionIdentityTagEnum.getValue());
        List<UserQuestionKeyIdentity> userQuestionKeyIdentityList = userQuestionKeyIdentityMapperExt.selectKeywordByUserTag(questionIdentityTagEnum.getValue());
        for(UserQuestionKeyIdentity userQuestionKeyIdentity:userQuestionKeyIdentityList){
            KeyWordResponseDTO keyWordResponseDTO = new KeyWordResponseDTO();
            UserQuestionKey userQuestionKey = userQuestionKeyMapper.selectByPrimaryKey(userQuestionKeyIdentity.getQuestionKeyId());
            keyWordResponseDTO.setId(userQuestionKey.getId());
            keyWordResponseDTO.setKeyWordName(userQuestionKey.getWord());
            keyWordResponseDTO.setKeyWordImgUrl(userQuestionKey.getImageUrl());
            keyWordResponseDTO.setKeyWordActiveImgUrl(userQuestionKey.getActiveImageUrl());
            KeywordList.add(keyWordResponseDTO);
        }
        dto.setKeywordList(KeywordList);
        return dto;
    }

    /**
     * 关键词查询问题列表
     * @param keyWordId
     * @return
     */
    public ProblemListResponseDTO queryProblemListByKeyword(Long keyWordId,String userId) {
        UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);

        QuestionIdentityTagEnum questionIdentityTagEnum = queryUserIdentity(userBasicInfo);
        //按更新时间排序前五
        List<UserQuestion>  userQuestionOrder=userQuestionMapperExt.selectByPrimaryKeyOrder();

        List<QuestionKeyRelation> questionKeyRelationList = userQuestionKeyRelationMapperExt.selectProblemIdByKey(keyWordId);
        log.info("关键词查询问题 questionKeyRelationList info{}"+questionKeyRelationList.toArray());
        ProblemListResponseDTO problemListResponseDTO=new ProblemListResponseDTO();
        List<ProblemResponseDTO> borrowHotProblemsList=new ArrayList<>();
        problemListResponseDTO.setIdentityStatus(questionIdentityTagEnum.getValue());
        questionKeyRelationList.forEach(res->{
            UserQuestion userQuestion = userQuestionMapper.selectByPrimaryKey(res.getQuestionId());
            ProblemResponseDTO problemResponseDTO=new ProblemResponseDTO();
            problemResponseDTO.setId(userQuestion.getId());
            problemResponseDTO.setProblemName(userQuestion.getTitle());

            for(UserQuestion order:userQuestionOrder){
                if(userQuestion.getId().equals(order.getId())){
                    problemResponseDTO.setIsNew((byte)1);
                    break;
                }else{
                    problemResponseDTO.setIsNew((byte)0);
                }
            }
            borrowHotProblemsList.add(problemResponseDTO);
        });
        problemListResponseDTO.setBorrowHotProblemsList(borrowHotProblemsList);

        return  problemListResponseDTO;
    }

    /**
     * 查看问题详情
     * @param questionId
     * @return
     */
    public ProblemDetailResponseDTO showQuestionDetail(Long questionId,Long keywordId,String userId) {
        log.info("查看问题详情 showQuestionDetail keywordId="+keywordId);
        /*UserBasicInfo userBasicInfo = userBasicInfoMapperExt.selectByPrimaryKey(userId);

        QuestionIdentityTagEnum questionIdentityTagEnum = queryUserIdentity(userBasicInfo);*/

        ProblemDetailResponseDTO problemDetailResponseDTO=new ProblemDetailResponseDTO();
        UserQuestion userQuestion = userQuestionMapper.selectByPrimaryKey(questionId);
        problemDetailResponseDTO.setId(userQuestion.getId());
        problemDetailResponseDTO.setProblemName(userQuestion.getTitle());
        problemDetailResponseDTO.setAnswerContent(userQuestion.getContent());
        UserQuestionFeedBack userQuestionFeedBack=userQuestionFeedBackMapperExt.selectAnswerStatus(questionId,userId);
        if(StringUtils.isEmpty(userId)){
            problemDetailResponseDTO.setAnswerStatus((byte)-2);
        }else{
            if(userQuestionFeedBack!=null){
                if (userQuestionFeedBack.getUsefulState().equals(UsefulStateEnum.USEFUL.getValue())){
                    problemDetailResponseDTO.setAnswerStatus(userQuestionFeedBack.getUsefulState());
                }else if(userQuestionFeedBack.getUsefulState()==null){
                    problemDetailResponseDTO.setAnswerStatus((byte)-1);
                }else{
                    problemDetailResponseDTO.setAnswerStatus(UsefulStateEnum.USELESS.getValue());
                }
            }else{
                problemDetailResponseDTO.setAnswerStatus((byte)-1);
            }
        }
        //相关问题排序
        List<ProblemContentResponseDTO> problemList=new ArrayList<>();
        List<QuestionKeyRelation> questionKeyRelationList=new ArrayList<>();
        if(null!=keywordId){
            QuestionKeyRelation QuestionKeyRelation =  userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndId(keywordId,questionId);
            if(QuestionKeyRelation!=null){
                int orderNumber = QuestionKeyRelation.getOrderNumber();
                for(int i=1;i<=3;i++){
                    QuestionKeyRelation questionKeyRelationNew = userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndOrder(keywordId,(orderNumber+1));
                    if(questionKeyRelationNew==null){
                        int newOrderNumber=0;
                        for(int j=i;j<=3;j++){
                            questionKeyRelationNew = userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndOrder(keywordId,(newOrderNumber+1));
                            if(questionKeyRelationNew!=null){
                                if(orderNumber!=questionKeyRelationNew.getOrderNumber()){
                                    questionKeyRelationList.add(questionKeyRelationNew);
                                    newOrderNumber=newOrderNumber+1;
                                }
                            }
                        }
                        break;
                    }
                    questionKeyRelationList.add(questionKeyRelationNew);
                    orderNumber=orderNumber+1;
                }
            }

        }else{
            //取orderNumber最前的关键词
            QuestionKeyRelation questionKeyRelation = userQuestionKeyRelationMapperExt.selectProblemByQuestionAndIdentity(questionId);
            if(questionKeyRelation!=null){
                keywordId= questionKeyRelation.getKeywordId();
                QuestionKeyRelation QuestionKeyRelation =  userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndId(keywordId,questionId);
                if(QuestionKeyRelation!=null){
                    int orderNumber = QuestionKeyRelation.getOrderNumber();
                    for(int i=1;i<=3;i++){
                        QuestionKeyRelation questionKeyRelationNew = userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndOrder(keywordId,(orderNumber+1));
                        if(questionKeyRelationNew==null){
                            int newOrderNumber=0;
                            for(int j=i;j<=3;j++){
                                questionKeyRelationNew = userQuestionKeyRelationMapperExt.selectProblemIdByKeyAndOrder(keywordId,(newOrderNumber+1));
                                if(questionKeyRelationNew!=null){
                                    if(orderNumber!=questionKeyRelationNew.getOrderNumber()){
                                        questionKeyRelationList.add(questionKeyRelationNew);
                                        newOrderNumber=newOrderNumber+1;
                                    }
                                }
                            }
                            break;
                        }
                        questionKeyRelationList.add(questionKeyRelationNew);
                        orderNumber=orderNumber+1;
                    }
                }
            }
        }

        questionKeyRelationList.forEach(res->{
            if(!questionId.equals(res.getQuestionId())){
                UserQuestion userQuestions = userQuestionMapper.selectByPrimaryKey(res.getQuestionId());
                ProblemContentResponseDTO problemContentResponseDTO=new ProblemContentResponseDTO();
                problemContentResponseDTO.setId(userQuestions.getId());
                problemContentResponseDTO.setProblemTitle(userQuestions.getTitle());
                problemList.add(problemContentResponseDTO);
            }
        });
        problemDetailResponseDTO.setProblemList(problemList);
        return problemDetailResponseDTO;
    }

    /**
     * 修改问题状态(有用无用)
     * @param requestDTO
     * @return
     */
    @Transactional()
    public int  updateAnswerStatus(ProblemStatusRequestDTO requestDTO) {
        UserQuestionFeedBack userQuestionFeedBack=userQuestionFeedBackMapperExt.selectAnswerStatus(requestDTO.getQuestionId(),requestDTO.getUserId());
        UserQuestionFeedBack userQuestionFeedBack1=new UserQuestionFeedBack();
        userQuestionFeedBack1.setUserId(requestDTO.getUserId());
        userQuestionFeedBack1.setQuestionId(requestDTO.getQuestionId());
        userQuestionFeedBack1.setCreateTime(new Date());
        userQuestionFeedBack1.setUpdateTime(new Date());
        int num =0;
        if(!requestDTO.getStatus().equals((byte)-1)) {
            userQuestionFeedBack1.setUsefulState(requestDTO.getStatus());
            if(userQuestionFeedBack==null){
                userQuestionFeedBack1.setId(snowflakeIdWorker.nextId());
                num = userQuestionFeedBackMapperExt.insertSelective(userQuestionFeedBack1);
            }else{
                userQuestionFeedBack1.setId(userQuestionFeedBack.getId());
                num=userQuestionFeedBackMapperExt.updateByPrimaryKeySelective(userQuestionFeedBack1);
            }
        }else {
            num = userQuestionFeedBackMapperExt.deleteByUserIdAndStatus(requestDTO.getQuestionId(), requestDTO.getUserId());
        }
        return num;
    }
    /**
     * 修改完有用无用状态后再查看最新状态
     */
    public ProblemStatusResponseDTO  queryNewQuestionStatus(int num,ProblemStatusRequestDTO requestDTO){
        ProblemStatusResponseDTO dto = new ProblemStatusResponseDTO();
        if(num>0){
            UserQuestionFeedBack userQuestionFeedBack3=userQuestionFeedBackMapperExt.selectAnswerStatusByStatus(requestDTO);

            if(userQuestionFeedBack3!=null){
                dto.setAnswerStatus(userQuestionFeedBack3.getUsefulState());
            }else{
                dto.setAnswerStatus((byte)-1);
            }
        }
        return dto;
    }

    /**
     * 保存反馈结果
     * @param requestDTO
     * @return
     */
    public boolean saveFeedBackInfo(NewFeedBackSaveRequestDTO requestDTO) {
        UserNewFeedBack userNewFeedBack=new UserNewFeedBack();
        userNewFeedBack.setId(snowflakeIdWorker.nextId());
        userNewFeedBack.setUserId(requestDTO.getUserId());
        userNewFeedBack.setDeviceType(requestDTO.getDeviceType());
        userNewFeedBack.setType(requestDTO.getType());
        //反馈内容存在emoji表情时，先转为字符串入库
        userNewFeedBack.setContent(EmojiParser.parseToAliases(requestDTO.getContent()));

        userNewFeedBack.setDeviceSystem(requestDTO.getDeviceSystem());
        userNewFeedBack.setAppVersion(requestDTO.getAppVersion());
        if(requestDTO.getFeedBackImgUrl()!=null && !requestDTO.getFeedBackImgUrl().isEmpty()){
            userNewFeedBack.setIsImages((byte)1);
            List<String> feedBackImgUrlList=requestDTO.getFeedBackImgUrl();
            feedBackImgUrlList.forEach(res->{
                UserFeedBackImage userFeedBackImage=new UserFeedBackImage();
                userFeedBackImage.setId(snowflakeIdWorker.nextId());
                userFeedBackImage.setFdId(userNewFeedBack.getId());
                userFeedBackImage.setImageType(FeedbackImageTypeEnum.FEEDBACK.getValue());
                userFeedBackImage.setImageUrl(res);
                userFeedBackImageMapper.insert(userFeedBackImage);
            });
        }else{
            userNewFeedBack.setIsImages((byte)0);
        }

        userNewFeedBack.setCreateTime(new Date());
        userNewFeedBack.setUpdateTime(new Date());

        //保存反馈时就是待回复状态
        userNewFeedBack.setStatus(FeedbackStatusEnum.WAIT_REPLY.getValue());
        userNewFeedBack.setSubStatus(FeedbackSubStatusEnum.WAIT_REPLY.getValue());
        userNewFeedBack.setAcceptStatus(FeedBackSaveEunm.UNKNOWN.getValue());
        userNewFeedBack.setHandleStatus(FeedBackSaveEunm.UNKNOWN.getValue());
        userNewFeedBack.setUsefulFlag((byte)0);
        userNewFeedBack.setUpdateManager(0L);
        userNewFeedBack.setUpdateManagerName("");
        return userNewFeedBackMapperExt.insertSelective(userNewFeedBack)> 0;
    }

    /**
     * 查询反馈记录
     * @param requestDTO
     * @return
     */
    public PageResponseDTO<FeedBackInfoResponseDTO> showFeedBackRecord(NiiwooScorePageRequestDTO requestDTO){
        PageResponseDTO<FeedBackInfoResponseDTO> page = new PageResponseDTO<FeedBackInfoResponseDTO>();

        int totalCount = userNewFeedBackMapperExt.selectCountFeedBackList(requestDTO);
        if(totalCount <1){
            return page;
        }
        List<UserNewFeedBack> userNewFeedBackList=userNewFeedBackMapperExt.selectByUserId(requestDTO);
        List<FeedBackInfoResponseDTO> feedBackInfoList=new ArrayList<>();
        userNewFeedBackList.forEach(res->{
            FeedBackInfoResponseDTO feedBackInfoResponseDTO=new FeedBackInfoResponseDTO();
            feedBackInfoResponseDTO.setId(res.getId());
            feedBackInfoResponseDTO.setIsImage(res.getIsImages());
            feedBackInfoResponseDTO.setFeedBackTitle(EmojiParser.parseToUnicode(res.getContent()));
            if(res.getSubStatus().equals(FeedbackSubStatusEnum.REPLIED_WAIT_VIEW.getValue())){
                feedBackInfoResponseDTO.setIsNewReceived((byte)1);
            }else{
                feedBackInfoResponseDTO.setIsNewReceived((byte)0);
            }
            feedBackInfoResponseDTO.setFeedBackStatus(res.getStatus());
            feedBackInfoResponseDTO.setFeedBackSubStatus(res.getSubStatus());
            feedBackInfoResponseDTO.setFeedBackTime(res.getCreateTime());
            feedBackInfoList.add(feedBackInfoResponseDTO);
        });
        page.setTotalCount(totalCount);
        page.setItems(feedBackInfoList);
        page.measureTotalPage(totalCount,requestDTO.getPageSize());
        return page;
    }

    /**
     * 反馈详情
     * @param requestDTO
     * @return
     */
    @Transactional
    public FeedBackDetailResponseDTO feedBackDetails(FeedBackDetailRequestDTO requestDTO){
        FeedBackDetailResponseDTO feedBackDetailResponseDTO=new FeedBackDetailResponseDTO();
        UserNewFeedBack userNewFeedBack=userNewFeedBackMapperExt.selectByPrimaryKey(requestDTO.getId());
        feedBackDetailResponseDTO.setId(userNewFeedBack.getId());
        feedBackDetailResponseDTO.setFeedBackType(userNewFeedBack.getType());
        ////反馈内容存在emoji表情时，显示时转为表情
        feedBackDetailResponseDTO.setFeedBackContent(EmojiParser.parseToUnicode(userNewFeedBack.getContent()));
        //反馈图片地址
        List<UserFeedBackImage> feedBackImageList=userFeedBackImageMapperExt.selectByImgType(requestDTO.getId(),FeedbackImageTypeEnum.FEEDBACK.getValue());
        if(feedBackImageList!=null){
            List<String> feedBackImgUr=new ArrayList<>();
            feedBackImageList.forEach(res->{
                feedBackImgUr.add(res.getImageUrl());
            });
            feedBackDetailResponseDTO.setFeedBackImgUrl(feedBackImgUr);
        }
        feedBackDetailResponseDTO.setFeedBackTime(userNewFeedBack.getCreateTime());
        feedBackDetailResponseDTO.setFeedBackStatus(userNewFeedBack.getStatus());
        feedBackDetailResponseDTO.setFeedBackSubStatus(userNewFeedBack.getSubStatus());
        if(userNewFeedBack.getSubStatus().equals(FeedbackSubStatusEnum.REPLIED_WAIT_VIEW.getValue())){
            UserNewFeedBack userNewFeedBack1=new UserNewFeedBack();
            userNewFeedBack1.setId(requestDTO.getId());
            userNewFeedBack1.setSubStatus(FeedbackSubStatusEnum.REPLIED_VIEWED.getValue());
            userNewFeedBackMapperExt.updateByPrimaryKeySelective(userNewFeedBack1);
        }
        List<AppendOrReplyContent> appendOrReplyContentList=new ArrayList<>();
        List<UserFeedBackAppend> userFeedBackAppendList = userFeedBackAppendMapperExt.selectByFeedBackId(requestDTO.getId());
        userFeedBackAppendList.forEach(res->{
            AppendOrReplyContent appendOrReplyContent=new AppendOrReplyContent();
            //追加内容存在emoji表情时，显示时转为表情
            appendOrReplyContent.setAppendContent(EmojiParser.parseToUnicode(res.getContent()));
            //追加图片地址
            if(res.getAppendType().equals(FeedbackAppendTypeEnum.APPEND.getValue())){
                List<String> appendImgUrl=new ArrayList<>();
                List<UserFeedBackImage> appendImageList=userFeedBackImageMapperExt.selectByImgType(res.getId(),FeedbackImageTypeEnum.APPEND.getValue());
                if(appendImageList!=null){
                    appendImageList.forEach(appendImage->{
                        appendImgUrl.add(appendImage.getImageUrl());
                    });
                    appendOrReplyContent.setAppendImgUrl(appendImgUrl);
                }
            }
            appendOrReplyContent.setAppendTime(res.getCreateTime());
            appendOrReplyContent.setAppendType(res.getAppendType());
            appendOrReplyContentList.add(appendOrReplyContent);
        });
        feedBackDetailResponseDTO.setAppendOrReplyContentList(appendOrReplyContentList);
        return feedBackDetailResponseDTO;
    }

    /**
     * 追加反馈
     * @param requestDTO
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public boolean appendFeedBackInfo(AppendFeedBackRequestDTO requestDTO){
        UserFeedBackAppend userFeedBackAppend=new UserFeedBackAppend();
        userFeedBackAppend.setId(snowflakeIdWorker.nextId());
        userFeedBackAppend.setAppendType((byte)0);
        userFeedBackAppend.setFeedbackId(requestDTO.getId());
        //追加内容存在emoji表情时，存入时转为字符串
        userFeedBackAppend.setContent(EmojiParser.parseToAliases(requestDTO.getFeedBackContent()));
        userFeedBackAppend.setCreateTime(new Date());
        //是否有图（1-是，0-否）
        if(requestDTO.getFeedBackImgUrl()!=null && !requestDTO.getFeedBackImgUrl().isEmpty()){
            userFeedBackAppend.setIsImages((byte)1);
            List<String> feedBackImgUrlList=requestDTO.getFeedBackImgUrl();
            feedBackImgUrlList.forEach(res->{
                UserFeedBackImage userFeedBackImage=new UserFeedBackImage();
                userFeedBackImage.setId(snowflakeIdWorker.nextId());
                userFeedBackImage.setFdId(userFeedBackAppend.getId());
                userFeedBackImage.setImageType(FeedbackImageTypeEnum.APPEND.getValue());
                userFeedBackImage.setImageUrl(res);
                userFeedBackImageMapper.insert(userFeedBackImage);
            });
        }else{
            userFeedBackAppend.setIsImages((byte)0);
        }

        UserNewFeedBack userNewFeedBack=userNewFeedBackMapperExt.selectByPrimaryKey(requestDTO.getId());
        if(userNewFeedBack!=null && userNewFeedBack.getStatus().equals(FeedbackStatusEnum.REPLIED.getValue())){
            UserNewFeedBack userNewFeedBackUp=new UserNewFeedBack();
            userNewFeedBackUp.setId(userNewFeedBack.getId());
            userNewFeedBackUp.setStatus(FeedbackStatusEnum.WAIT_REPLY.getValue());
            userNewFeedBackUp.setSubStatus(FeedbackSubStatusEnum.WAIT_REPLY.getValue());
            userNewFeedBackMapperExt.updateByPrimaryKeySelective(userNewFeedBackUp);
        }
        return userFeedBackAppendMapperExt.insertSelective(userFeedBackAppend)>0;
    }

    /**
     *反馈解决状态
     * @param requestDTO
     * @return
     */
    @Transactional
    public boolean feedBackSolveStatus(FeedBackStatusRequestDTO requestDTO){
        UserNewFeedBack userNewFeedBack=new UserNewFeedBack();
        userNewFeedBack.setId(requestDTO.getId());
        userNewFeedBack.setUpdateTime(new Date());
        if(requestDTO.getStatus().equals(FeedbackStatusEnum.SOLVE.getValue().toString())){
            userNewFeedBack.setStatus(FeedbackStatusEnum.SOLVE.getValue());
            userNewFeedBack.setSubStatus(FeedbackSubStatusEnum.SOLVED.getValue());
        }else if(requestDTO.getStatus().equals(FeedbackSubStatusEnum.UNSOLVED.getValue())){
            userNewFeedBack.setStatus(FeedbackStatusEnum.REPLIED.getValue());
            userNewFeedBack.setSubStatus(FeedbackSubStatusEnum.UNSOLVED.getValue());
        }

        return  (userNewFeedBackMapperExt.updateByPrimaryKeySelective(userNewFeedBack)>0);
    }

    /**
     * 统计问题/关键词 PV和UV
     * @param requestDTO
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public boolean accountPVAndUV(AccountPVAndUVRequestDTO requestDTO,String session){
        log.info("AccountPVAndUVRequestDTO info{}"+requestDTO.getKeywordId(),requestDTO.getQuestionId(),session);
        String userIdOrdeviceIdKey=session+UserRedisKey.CUSTOMER_ACCOUNT_UV_SESSION_ID ;
        String  userIdOrdeviceId = redisTemplate.opsForValue().get(userIdOrdeviceIdKey);
        StringBuffer buffer=new StringBuffer("");
        String clickTime = dateFormat.format(requestDTO.getTime());
        if(requestDTO.getUserId()!=null){
            buffer=new StringBuffer(requestDTO.getUserId());
            buffer.append(clickTime);
        }else{
            buffer=new StringBuffer(requestDTO.getDeviceId());
            buffer.append(clickTime);
        }
        if(null!=requestDTO.getQuestionId()){
            UserQuestion userQuestion=userQuestionMapper.selectByPrimaryKey(requestDTO.getQuestionId());
            int pvNumber=userQuestion.getPv()+1;
            int uvNumber=userQuestion.getUv();
            String questions=buffer.toString();

            if(!questions.equals(userIdOrdeviceId)){
                redisTemplate.opsForValue().set(userIdOrdeviceIdKey, questions);
                uvNumber=uvNumber+1;
            }
            UserQuestion userQuestionNew=new UserQuestion();
            userQuestionNew.setId(requestDTO.getQuestionId());
            userQuestionNew.setPv(pvNumber);
            userQuestionNew.setUv(uvNumber);
            return userQuestionMapper.updateByPrimaryKeySelective(userQuestionNew)>0;
        }
        if(null!=requestDTO.getKeywordId()){
            UserQuestionKey userQuestionKey= userQuestionKeyMapper.selectByPrimaryKey(requestDTO.getKeywordId());
            int wordPvNumber=userQuestionKey.getPv()+1;
            int wordUvNumber=userQuestionKey.getUv();
            String keywords=buffer.toString();
            if(!keywords.equals(userIdOrdeviceId)){
                redisTemplate.opsForValue().set(userIdOrdeviceIdKey, keywords);
                wordUvNumber=wordUvNumber+1;
            }
            UserQuestionKey userQuestionKeyNew = new UserQuestionKey();
            userQuestionKeyNew.setId(requestDTO.getKeywordId());
            userQuestionKeyNew.setPv(wordPvNumber);
            userQuestionKeyNew.setUv(wordUvNumber);
            return userQuestionKeyMapper.updateByPrimaryKeySelective(userQuestionKeyNew)>0;
        }
        return  false;
    }
    /**
     * 统计有用，无用按钮的点击数
     * @param requestDTO
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void accountButtonPVAndUV(ProblemStatusRequestDTO requestDTO){
        UserQuestion userQuestion=userQuestionMapper.selectByPrimaryKey(requestDTO.getQuestionId());
        log.info("userQuestion info{}"+userQuestion.toString());
        UserQuestion UserQuestion1=new UserQuestion();
        UserQuestion1.setId(userQuestion.getId());
        if(requestDTO.getStatus().equals(UsefulStateEnum.USEFUL.getValue())){
            if(userQuestion.getUseful()!=null){
                UserQuestion1.setUseful(userQuestion.getUseful()+1);
                userQuestionMapper.updateByPrimaryKeySelective(UserQuestion1);
            }else{
                UserQuestion1.setUseful(1);
                userQuestionMapper.updateByPrimaryKeySelective(UserQuestion1);
            }
        }else if(requestDTO.getStatus().equals(UsefulStateEnum.USELESS.getValue())){
            if(userQuestion.getUseless()!=null){
                UserQuestion1.setUseless(userQuestion.getUseless()+1);
                userQuestionMapper.updateByPrimaryKeySelective(UserQuestion1);
            }else{
                UserQuestion1.setUseless(1);
                userQuestionMapper.updateByPrimaryKeySelective(UserQuestion1);
            }
        }
    }
    /**
     * 反馈是否最新回复
     * @param userId
     * @return
     */
    public FeedBackIsNewReceiveResponseDTO feedBackisNewReceive(String userId) {
        FeedBackIsNewReceiveResponseDTO feedBackIsNewReceiveResponseDTO = new FeedBackIsNewReceiveResponseDTO();

        UserNewFeedBack userNewFeedBack = userNewFeedBackMapperExt.selectFeedBackIsNewStatus(userId);
        if (userNewFeedBack == null || StringUtils.isEmpty(userId)) {
            feedBackIsNewReceiveResponseDTO.setIsNewReceive(( byte ) 0);
        } else {
            feedBackIsNewReceiveResponseDTO.setIsNewReceive(( byte ) 1);
        }
        return feedBackIsNewReceiveResponseDTO;
    }

    /**
     * 获取用户输入数据长度
     */
    public double getLength(String word) {
        double valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < word.length(); i++) {
            String temp = word.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 1;
            } else {
                valueLength += 0.5;
            }
        }
        return valueLength;
    }


}



